package com.example.aigc_education.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.aigc_education.domain.Checklist;
import com.example.aigc_education.domain.Plan;
import com.example.aigc_education.domain.Todo;
import com.example.aigc_education.service.ChecklistService;
import com.example.aigc_education.service.PlanService;
import com.example.aigc_education.service.TodoService;
import com.example.aigc_education.utils.SecurityUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * 预刷新任务
 */
@Component
@EnableScheduling
public class PreRefreshJob {

    @Resource
    private TodoService todoService;

    @Resource
    private PlanService planService;

    @Resource
    private ChecklistService checklistService;

    /**
     * 刷新待办事项列表 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void refreshTodoList() {

        List<Object> planIdList = planService.listObjs(new QueryWrapper<Plan>().select("plan_id"));
        for(Object planId : planIdList) {
            List<Todo> currentTodoList = todoService.list(new QueryWrapper<Todo>().eq("plan_id", planId).eq("is_current_chapter", 1));
            List<Todo> isNonCompleteTodoList = todoService.list(new QueryWrapper<Todo>().eq("plan_id", planId).eq("is_complete", 0));

            if (isNonCompleteTodoList.size() == 0) {
                continue;
            }
            boolean hasIncompleteTodo = false;
            for (Todo currentTodo : currentTodoList) {
                if (currentTodo.getIsComplete() == 0) {
                    hasIncompleteTodo = true;
                    break;
                }
            }

            if (!hasIncompleteTodo) {
                for (Todo currentTodo : currentTodoList) {
                    currentTodo.setIsCurrentChapter(0);
                    todoService.updateById(currentTodo);
                }
                // 通过找出isNonCompleteTodoList最小的todoId，读取出其章节
                Long minTodoId = findMinTodoId(isNonCompleteTodoList);
                Todo nextTodo = todoService.getOne(new LambdaQueryWrapper<Todo>().eq(Todo::getTodoId, minTodoId));
                // chapter && planId
                QueryWrapper<Todo> queryWrapper = new QueryWrapper<Todo>().eq("chapter", nextTodo.getChapter()).eq("plan_id", nextTodo.getPlanId());
                List<Todo> nextTodoList = todoService.list(queryWrapper);
                nextTodoList.forEach(todo -> {
                    todo.setIsCurrentChapter(1);
                    todoService.updateById(todo);
                });
            }
        }
    }

    private Long findMinTodoId(List<Todo> todoList) {
        Long minTodoId = Long.MAX_VALUE;
        for (Todo todo : todoList) {
            if (todo.getTodoId() < minTodoId) {
                minTodoId = todo.getTodoId();
            }
        }
        return minTodoId;
    }


    /**
     * 刷新待办
     * 1.循环刷新
     * 2.今日已做清0
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void refreshCheckList() {
        // 1.将所有今日状态修改为普通状态
        LambdaUpdateWrapper<Checklist> updateWrapperForTodayStatus = new LambdaUpdateWrapper<>();
        updateWrapperForTodayStatus.setSql("checklist_status = case when checklist_status = 1 then 3 when checklist_status = 2 then 4 else checklist_status end");
        checklistService.update(null, updateWrapperForTodayStatus);
        // 2 循环刷新
        LambdaUpdateWrapper<Checklist> updateWrapperForRepeat = new LambdaUpdateWrapper<>();
        //2.1 筛选出循环不计时待办类型
        updateWrapperForRepeat.eq(Checklist::getChecklistType,3).or().eq(Checklist::getChecklistType,4);
        //2.2 刷新
        updateWrapperForRepeat.set(Checklist::getChecklistStatus,0);
        updateWrapperForRepeat.set(Checklist::getTimeDuration,0);
        updateWrapperForRepeat.set(Checklist::getTimingDate,null);
        checklistService.update(updateWrapperForRepeat);
        //3 今日已做清0
        LambdaUpdateWrapper<Checklist> updateWrapperForNewDay = new LambdaUpdateWrapper<>();
        //筛选出大于今日已做时间>0
        updateWrapperForNewDay.ge(Checklist::getTodayDoTime,0);
        updateWrapperForNewDay.set(Checklist::getTodayDoTime,0);
        checklistService.update(updateWrapperForNewDay);
    }

    /**
     * 刷新计划学习时间
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void refreshPlanTime() {
        // 1.将所有今日状态修改为普通状态
        LambdaUpdateWrapper<Plan> updateWrapperForPlanTime = new LambdaUpdateWrapper<>();
        // 设置更新条件，这里假设更新所有记录
        updateWrapperForPlanTime.eq(Plan::getStatus,1);
        updateWrapperForPlanTime.setSql("study_time = CONCAT(SUBSTRING_INDEX(study_time, ',', -6), ',0')");
        planService.update(updateWrapperForPlanTime);
    }

}
